import os
import shutil
from PIL import Image

# 设置源文件夹路径和目标文件夹路径
folder_path = '/home/shuai/notebook/note_scripts/boat/images'
target_folder_path = '/home/shuai/notebook/note_scripts/boat/images_jpg'

# 如果目标文件夹不存在，则创建目标文件夹
os.makedirs(target_folder_path, exist_ok=True)

# 获取文件夹中的所有文件
for filename in os.listdir(folder_path):
    file_path = os.path.join(folder_path, filename)
    
    # 检查文件是否为图片文件
    if os.path.isfile(file_path):
        try:
            with Image.open(file_path) as img:
                # 处理JPEG格式的图片
                if img.format == 'JPEG':
                    # 将文件名后缀统一为 .jpg
                    new_filename = os.path.splitext(filename)[0] + '.jpg'
                    new_file_path = os.path.join(target_folder_path, new_filename)
                    
                    # 复制文件到目标文件夹
                    shutil.copy(file_path, new_file_path)
                    print(f"已复制: {filename} -> {new_filename}")
                else:
                    # 只处理非JPEG格式的文件
                    new_filename = os.path.splitext(filename)[0] + '.jpg'
                    new_file_path = os.path.join(target_folder_path, new_filename)
                    
                    # 转换并保存为JPG格式
                    img.convert('RGB').save(new_file_path, 'JPEG')
                    print(f"已转换并复制: {filename} -> {new_filename}")
        except Exception as e:
            print(f"无法处理文件 {filename}: {e}")
